<template>
  <div class="interview-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 面试基本信息 -->
    <div v-else class="interview-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="interview-title">{{ interview.title }}</h1>
          <el-tag 
            :type="getStatusType(interview.status)"
            size="large"
            class="status-tag"
          >
            {{ getStatusText(interview.status) }}
          </el-tag>
        </div>
        
        <div class="header-actions">
          <el-button @click="editInterview">
            <el-icon><Edit /></el-icon>
            编辑面试
          </el-button>
          <el-button type="primary" @click="viewStatistics">
            <el-icon><DataAnalysis /></el-icon>
            查看统计
          </el-button>
          <el-dropdown @command="handleCommand">
            <el-button>
              更多操作
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="duplicate">
                  <el-icon><CopyDocument /></el-icon>
                  复制面试
                </el-dropdown-item>
                <el-dropdown-item command="export">
                  <el-icon><Download /></el-icon>
                  导出数据
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>
                  <el-icon><Delete /></el-icon>
                  删除面试
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <div class="interview-meta">
        <div class="meta-item">
          <el-icon><OfficeBuilding /></el-icon>
          <span>{{ interview.position }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Calendar /></el-icon>
          <span>创建时间：{{ formatDate(interview.createdAt) }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Clock /></el-icon>
          <span>预计时长：{{ interview.estimatedDuration }}分钟</span>
        </div>
        <div class="meta-item">
          <el-icon><User /></el-icon>
          <span>{{ interview.candidateCount }}名候选人</span>
        </div>
      </div>
    </div>

    <!-- 面试概览 -->
    <div class="overview-section">
      <div class="overview-card">
        <div class="card-header">
          <h3>面试进度</h3>
        </div>
        <div class="progress-content">
          <div class="progress-stats">
            <div class="stat-item">
              <div class="stat-number">{{ interview.completedCount }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ interview.inProgressCount }}</div>
              <div class="stat-label">进行中</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ interview.pendingCount }}</div>
              <div class="stat-label">待开始</div>
            </div>
          </div>
          <div class="progress-bar">
            <el-progress 
              :percentage="getProgressPercentage()" 
              :color="getProgressColor()"
              :stroke-width="12"
              :show-text="false"
            />
            <span class="progress-text">{{ getProgressPercentage() }}%</span>
          </div>
        </div>
      </div>
      
      <div class="overview-card">
        <div class="card-header">
          <h3>通过率统计</h3>
        </div>
        <div class="stats-content">
          <div class="stats-chart">
            <div class="chart-circle">
              <div class="circle-progress">
                <span class="progress-value">{{ interview.passRate }}%</span>
              </div>
            </div>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-dot success"></div>
                <span>通过：{{ interview.passedCount }}</span>
              </div>
              <div class="legend-item">
                <div class="legend-dot danger"></div>
                <span>未通过：{{ interview.rejectedCount }}</span>
              </div>
              <div class="legend-item">
                <div class="legend-dot warning"></div>
                <span>待评估：{{ interview.pendingEvaluationCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="overview-card">
        <div class="card-header">
          <h3>面试阶段</h3>
        </div>
        <div class="stages-content">
          <div 
            v-for="stage in interview.stages" 
            :key="stage.id"
            class="stage-item"
          >
            <div class="stage-header">
              <span class="stage-name">{{ stage.name }}</span>
              <span class="stage-count">正在进行</span>
            </div>
            <div class="stage-description">{{ stage.description }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 候选人列表 -->
    <div class="candidates-section">
      <div class="section-header">
        <h2>候选人列表</h2>
        <div class="header-controls">
          <el-input 
            v-model="searchQuery" 
            placeholder="搜索候选人"
            prefix-icon="Search"
            size="small"
            clearable
          />
          <el-select v-model="statusFilter" placeholder="筛选状态" size="small" clearable>
            <el-option label="全部" value="" />
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="in-progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="通过" value="passed" />
            <el-option label="未通过" value="rejected" />
          </el-select>
        </div>
      </div>
      
      <div class="candidates-table">
        <el-table :data="filteredCandidates" style="width: 100%">
          <el-table-column prop="name" label="姓名" width="150">
            <template #default="scope">
              <div class="candidate-info">
                <el-avatar :src="scope.row.avatar" :size="32">
                  {{ scope.row.name.charAt(0) }}
                </el-avatar>
                <span class="candidate-name">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="phone" label="联系方式" width="150">
            <template #default="scope">
              <div class="contact-info">
                <div>{{ scope.row.phone }}</div>
                <div class="email">{{ scope.row.email }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="面试进度" width="200">
            <template #default="scope">
              <div class="progress-info">
                <div class="progress-bar-small">
                  <el-progress 
                    :percentage="scope.row.progress" 
                    :color="getProgressColor()"
                    :stroke-width="6"
                    :show-text="false"
                  />
                </div>
                <span class="progress-text">{{ scope.row.currentStage }}/{{ interview.stages.length }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="综合得分" width="120">
            <template #default="scope">
              <div class="score-cell">
                <span class="score-number">{{ scope.row.overallScore || '-' }}</span>
                <div class="score-stars" v-if="scope.row.overallScore">
                  <el-rate 
                    v-model="scope.row.scoreStars" 
                    disabled 
                    :max="5"
                    size="small"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.status)"
                size="small"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="最后活动" width="150">
            <template #default="scope">
              <div class="activity-info">
                <div class="activity-time">{{ formatDate(scope.row.lastActivity) }}</div>
                <div class="activity-action">{{ scope.row.lastAction }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="viewCandidateReport(scope.row.id)"
                >
                  查看报告
                </el-button>
                <el-button 
                  size="small"
                  @click="viewPlayback(scope.row.id)"
                  :disabled="scope.row.status !== 'completed'"
                >
                  观看回放
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 面试描述 -->
    <div class="description-section">
      <div class="section-header">
        <h2>面试描述</h2>
      </div>
      <div class="description-content">
        <p>{{ interview.description }}</p>
        <div class="description-tags">
          <el-tag 
            v-for="tag in interview.tags" 
            :key="tag"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { businessApi as api, hrApi } from '@/services/api'
import { 
  Edit, 
  DataAnalysis, 
  ArrowDown, 
  CopyDocument, 
  Download, 
  Delete,
  OfficeBuilding, 
  Calendar, 
  Clock, 
  User 
} from '@element-plus/icons-vue'

export default {
  name: 'InterviewDetailView',
  components: {
    Edit,
    DataAnalysis,
    ArrowDown,
    CopyDocument,
    Download,
    Delete,
    OfficeBuilding,
    Calendar,
    Clock,
    User
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 筛选条件
    const searchQuery = ref('')
    const statusFilter = ref('')
    
    // 面试详情数据
    const interview = ref({})
    const loading = ref(true)
    
    // 候选人数据
    const candidates = ref([])
    
    // 计算属性
    const filteredCandidates = computed(() => {
      let filtered = candidates.value.slice()
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(candidate => 
          candidate.name.toLowerCase().includes(query) ||
          candidate.phone.includes(query) ||
          candidate.email.toLowerCase().includes(query)
        )
      }
      
      // 状态过滤
      if (statusFilter.value) {
        filtered = filtered.filter(candidate => candidate.status === statusFilter.value)
      }
      
      return filtered
    })
    
    // 方法
    const editInterview = () => {
      router.push(`/hr/create-interview?edit=${interview.value.id}`)
    }
    
    const viewStatistics = () => {
      router.push(`/hr/statistics?interview=${interview.value.id}`)
    }
    
    const handleCommand = (command) => {
      switch (command) {
        case 'duplicate':
          console.log('复制面试')
          break
        case 'export':
          console.log('导出数据')
          break
        case 'delete':
          console.log('删除面试')
          break
      }
    }
    
    const viewCandidateReport = (candidateId) => {
      // 使用新的 HR 面试管理接口
      router.push(`/hr/interview-management/${candidateId}`)
    }
    
    const viewPlayback = (candidateId) => {
      router.push(`/hr/playback/${candidateId}`)
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }
    
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'in-progress': 'primary',
        'completed': 'info',
        'passed': 'success',
        'rejected': 'danger',
        'active': 'success'
      }
      return typeMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待开始',
        'in-progress': '进行中',
        'completed': '已完成',
        'passed': '通过',
        'rejected': '未通过',
        'active': '进行中'
      }
      return textMap[status] || '未知'
    }
    
    const getProgressPercentage = () => {
      if (interview.value.candidateCount === 0) return 0
      return Math.round((interview.value.completedCount / interview.value.candidateCount) * 100)
    }
    
    const getProgressColor = () => {
      const percentage = getProgressPercentage()
      if (percentage === 100) return '#67c23a'
      if (percentage >= 50) return '#409eff'
      return '#e6a23c'
    }
    
    // 加载面试详情数据
    const loadInterviewDetail = async () => {
      loading.value = true
      try {
        const interviewId = parseInt(route.params.id)
        
        // 直接调用面试详情API
        const response = await api.getInterviewDetail(interviewId)
        const data = response.data || response
        
        // 设置面试基本信息
        interview.value = {
          id: data.id,
          title: data.title,
          position: data.position,
          status: data.status,
          createdAt: data.created_at,
          estimatedDuration: data.estimated_duration,
          candidateCount: data.candidate_count,
          completedCount: data.completed_count,
          inProgressCount: data.in_progress_count,
          pendingCount: data.pending_count,
          passRate: data.pass_rate,
          passedCount: data.passed_count,
          rejectedCount: data.rejected_count,
          pendingEvaluationCount: data.pending_evaluation_count,
          description: data.description,
          tags: data.tags || [],
          stages: data.stages || []
        }
        
        // 设置候选人数据
        candidates.value = (data.candidates || []).map(candidate => ({
          id: candidate.id,
          name: candidate.name,
          phone: candidate.phone,
          email: candidate.email,
          avatar: candidate.avatar,
          progress: candidate.progress,
          currentStage: candidate.current_stage,
          overallScore: candidate.overall_score,
          scoreStars: candidate.score_stars,
          status: candidate.status,
          lastActivity: candidate.last_activity,
          lastAction: candidate.last_action
        }))
        
      } catch (error) {
        console.error('加载面试详情失败:', error)
        ElMessage.error('加载面试详情失败')
        
        // 使用默认数据
        interview.value = {
          id: parseInt(route.params.id),
          title: '面试详情',
          position: '未知职位',
          status: 'pending',
          createdAt: new Date().toISOString(),
          estimatedDuration: 60,
          candidateCount: 0,
          completedCount: 0,
          inProgressCount: 0,
          pendingCount: 0,
          passRate: 0,
          passedCount: 0,
          rejectedCount: 0,
          pendingEvaluationCount: 0,
          description: '暂无描述',
          tags: [],
          stages: []
        }
        candidates.value = []
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      loadInterviewDetail()
    })
    
    return {
      interview,
      loading,
      searchQuery,
      statusFilter,
      filteredCandidates,
      editInterview,
      viewStatistics,
      handleCommand,
      viewCandidateReport,
      viewPlayback,
      formatDate,
      getStatusType,
      getStatusText,
      getProgressPercentage,
      getProgressColor,
      loadInterviewDetail
    }
  }
}
</script>

<style scoped>
.interview-detail-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.loading-section {
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.interview-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.interview-title {
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.status-tag {
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.interview-meta {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-secondary);
  font-size: 14px;
}

.overview-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.progress-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--primary-color);
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.progress-bar {
  position: relative;
}

.progress-text {
  position: absolute;
  right: 0;
  top: -4px;
  font-size: 12px;
  color: var(--text-secondary);
}

.stats-content {
  display: flex;
  justify-content: center;
}

.stats-chart {
  display: flex;
  align-items: center;
  gap: 20px;
}

.chart-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: conic-gradient(#67c23a 0deg 270deg, #e4e7ed 270deg);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.chart-circle::before {
  content: '';
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: white;
  position: absolute;
}

.circle-progress {
  z-index: 1;
}

.progress-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color);
}

.chart-legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: var(--text-secondary);
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.legend-dot.success {
  background: #67c23a;
}

.legend-dot.danger {
  background: #f56c6c;
}

.legend-dot.warning {
  background: #e6a23c;
}

.stages-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stage-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.stage-name {
  font-weight: 600;
  color: var(--text-primary);
}

.stage-count {
  font-size: 12px;
  color: var(--text-secondary);
}

.stage-description {
  font-size: 12px;
  color: var(--text-secondary);
}

.candidates-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
}

.header-controls {
  display: flex;
  gap: 12px;
}

.candidates-table {
  margin-top: 16px;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.candidate-name {
  font-weight: 600;
  color: var(--text-primary);
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.contact-info .email {
  font-size: 12px;
  color: var(--text-secondary);
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar-small {
  flex: 1;
}

.progress-text {
  font-size: 12px;
  color: var(--text-secondary);
}

.score-cell {
  text-align: center;
}

.score-number {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.score-stars {
  margin-top: 4px;
}

.activity-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.activity-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.activity-action {
  font-size: 12px;
  color: var(--text-primary);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.description-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.description-content {
  color: var(--text-secondary);
  line-height: 1.6;
}

.description-content p {
  margin-bottom: 16px;
}

.description-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag-item {
  font-size: 12px;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .interview-meta {
    flex-direction: column;
    gap: 12px;
  }
  
  .overview-section {
    grid-template-columns: 1fr;
  }
  
  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-controls {
    flex-direction: column;
  }
}
</style> 